from rest_framework.views import exception_handler
from rest_framework_simplejwt.exceptions import InvalidToken, AuthenticationFailed

from apps.utils.response_utils import ResponseCode, api_response


def custom_jwt_exception_handler(exc, context):
    # 先获取DRF的默认响应
    response = exception_handler(exc, context)

    # 处理JWT认证错误
    if isinstance(exc, (InvalidToken, AuthenticationFailed)):
        error_code = ResponseCode.UNAUTHORIZED
        error_msg = '令牌无效或已过期'
        return api_response(code=error_code, msg=error_msg)

    # 其他异常使用默认处理
    return response